package com.ruoyi.system.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.Ptesting;
import com.ruoyi.system.domain.vo.PersonVo;
import com.ruoyi.system.domain.vo.checkExcelVo;
import com.ruoyi.system.mapper.DetectionCycleMapper;
import com.ruoyi.system.mapper.PtestingMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.domain.DetectionCycle;
import com.ruoyi.system.mapper.PersonMapper;
import com.ruoyi.system.domain.Person;
import com.ruoyi.system.service.IPersonService;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * personService业务层处理
 *
 * @author ruoyi
 * @date 2022-04-16
 */
@Service
public class PersonServiceImpl implements IPersonService {
    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private DetectionCycleMapper detectionCycleMapper;
    @Autowired
    private PtestingMapper ptestingMapper;
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    /**
     * 查询person
     *
     * @param personId person主键
     * @return person
     */
    @Override
    public Person selectPersonByPersonId(Long personId) throws ParseException {
        Person person = personMapper.selectPersonByPersonId(personId);
        person.setDeptName(gitDept(person.getDeptId())); //部门名称
        if (StringUtils.isNotNull(person.getDetectionCycleId())) {
            DetectionCycle detectionCycle = detectionCycleMapper.selectDetectionCycleById(person.getDetectionCycleId());
            long time = new Date().getTime();
            List<Map> dates1 = findDates(detectionCycle.getStartTime(), DateUtils.getDate(), detectionCycle.getFrequency());
            Map map = dates1.get((dates1.size() - 1));
            String starTime = map.get("starTime") + "";
            String entTime = map.get("entTime") + "";
            Ptesting ptesting = new Ptesting();
            ptesting.setStarTime(starTime + " 00:00:00");
            ptesting.setEntTime(entTime + " 23:59:59");
            ptesting.setPersonId(person.getPersonId());
            List<Ptesting> ptestings = ptestingMapper.selectPtestingList(ptesting);
            person.setPtestingList(ptestings);
        }


        return person;
    }


    public static List<Map> findDates(String stime, String etime, Long frequency) throws ParseException {
        List<String> dates = DateUtils.findDates(stime, etime);
        List<Map> list = new ArrayList();
        if (dates.size() > 0) {
            //能整除就不加，不能整除就加一
            int c = (int) ((int) dates.size() / frequency + (dates.size() % frequency != 0 ? 1 : 0));
            String staime = stime;
            for (int a = 0; a < c; a++) {
                Map map = new HashMap();
                map.put("starTime", staime);
                String s = DateUtils.dateTime(DateUtils.dateAddOne(DateUtils.parseDate(staime), Integer.parseInt((frequency - 1) + "")));
                staime = DateUtils.dateTime(DateUtils.dateAddOne(DateUtils.parseDate(staime), Integer.parseInt(frequency + "")));
                map.put("entTime", s);
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 查询person列表
     *
     * @param person person
     * @return person
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<Person> selectPersonList(Person person) {
        List<Person> peoples = personMapper.selectPersonList(person);
        for (Person persona : peoples) {
            persona.setDeptName(gitDept(persona.getDeptId()));
        }
        return peoples;
    }

    public String gitDept(Long dept) {
        String deptName = "";
        String[] split = ((sysDeptMapper.selectDeptById(dept).getAncestors()) + "," + dept).split(",");
        for (int a = 1; a < split.length; a++) {
            deptName += sysDeptMapper.selectDeptById(Long.valueOf(split[a])).getDeptName() + "-";
        }
        return deptName.substring(0, deptName.length() - 1);
    }

    /**
     * 新增person
     * pc
     *
     * @param person person
     * @return 结果
     */
    @Transactional
    @Override
    public int insertPerson(Person person) {
        person.setCreateTime(DateUtils.getNowDate());
        person.setCreateBy(getUsername());
        person.setExamine(0); //默认审核通过
        person.setSource("0");//数据来源
        int rows = personMapper.insertPerson(person);
        return rows;
    }

    /**
     * 新增person
     * 小程序
     *
     * @param person person
     * @return 结果
     */
    @Transactional
    @Override
    public int insertPersonXcx(Person person) {
        person.setCreateTime(DateUtils.getNowDate());
//        person.setCreateBy(getUsername());
        person.setExamine(1); //未审核通过
        int rows = personMapper.insertPerson(person);
        return rows;
    }

    /**
     * 修改person
     *
     * @param person person
     * @return 结果
     */
    @Transactional
    @Override
    public int updatePerson(Person person) {
        person.setUpdateTime(DateUtils.getNowDate());
        person.setCreateBy(getUsername());
        return personMapper.updatePerson(person);
    }

    /**
     * 批量删除person
     *
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePersonByPersonIds(Person person) {
        for (int a = 0; a < person.getPersonIds().length; a++) {
            Person perso = new Person();
            perso.setPersonId(Long.valueOf(person.getPersonIds()[a] + ""));
            perso.setReason(person.getReason());
            personMapper.deletePersonByPersonIds(perso);
        }
        return 1;
    }

    @Override
    public int truncateTable() {
        return personMapper.truncateTable();
    }

    /**
     * 删除person信息
     *
     * @param personId person主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePersonByPersonId(Long personId) {
        return personMapper.deletePersonByPersonId(personId);
    }

    /**
     * 新增${subTable.functionName}信息
     *
     * @param person person对象
     */
    public void insertDetectionCycle(Person person) {
        List<DetectionCycle> detectionCycleList = person.getDetectionCycleList();
        Long personId = person.getPersonId();
        if (StringUtils.isNotNull(detectionCycleList)) {
            List<DetectionCycle> list = new ArrayList<DetectionCycle>();
            for (DetectionCycle detectionCycle : detectionCycleList) {
                detectionCycle.setId(personId);
                list.add(detectionCycle);
            }
            System.out.println();
            if (list.size() > 0) {
                personMapper.batchDetectionCycle(list);
            }
        }
    }


    /**
     * 导入用户数据
     *
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String imporPerson(List<PersonVo> personList, Boolean isUpdateSupport) {


        if (StringUtils.isNull(personList) || personList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        //查詢类别
        List<PersonVo> personLists = new ArrayList<>();
        List<DetectionCycle> detectionCycles = detectionCycleMapper.selectDetectionCycleList(new DetectionCycle());
        //获取当前所有行业
        for (PersonVo personVo : personList) {
            //进行身份证号去重
            int asd = 0;
            for (PersonVo e : personList) {
                if (StringUtils.isNull(personVo.getCardId())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、姓名： " + personVo.getPersonName() + " 重复身份证号为空");
                    throw new ServiceException(failureMsg.toString());
                }
                if (personVo.getCardId().equals(e.getCardId())) {
                    asd++;

                }
            }
            if (asd > 1) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、姓名： " + personVo.getPersonName() + " 重复身份证号，身份证号为：" + personVo.getCardId());
                throw new ServiceException(failureMsg.toString());
            }
            List<SysDept> depts = deptService.selectDeptList(new SysDept());
            try {
                //行业匹配
                if (StringUtils.isNotEmpty(personVo.getDeptName())) {
                    String[] split = personVo.getDeptName().split("-");
                    int se = 0;
                    for (int a = 0; a < split.length; a++) {
                        String s = split[a].replaceAll(" ", "");//行业去空
                        for (int c = 0; c < depts.size(); c++) {
                            String s1 = depts.get(c).getDeptName().replaceAll(" ", "");
                            //最后一级
                            if (split.length == (a + 1)) {
                                if (s.equals(s1)) {
                                    personVo.setDeptId(depts.get(c).getDeptId());
                                    break;
                                }
                            }
                            if (s.equals(s1)) {
                                depts = deptService.selectDeptList(new SysDept(depts.get(c).getDeptId()));
                                se++;
                            }
                            if (depts.size() == (c + 1)) {
                                if (se == 0) {
                                    failureNum++;
                                    failureMsg.append("<br/>" + failureNum + "、姓名： " + personVo.getPersonName() + " 部门不匹配，部门名称为：" + s);
                                    throw new ServiceException(failureMsg.toString());
                                } else {
                                    se = 0;
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、姓名： " + personVo.getPersonName() + " 部门为空");
                    throw new ServiceException(failureMsg.toString());
                }
                if (StringUtils.isNull(personVo.getDeptId())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、姓名： " + personVo.getPersonName() + " 部门不匹配");
                    throw new ServiceException(failureMsg.toString());
                }

                //类别匹配
                String trim2 = personVo.getDetectionCycleName();
                if (StringUtils.isNotNull(trim2)) {
                    String s = trim2.replaceAll(" ", "");
                    for (int k = 0; k < detectionCycles.size(); k++) {
                        DetectionCycle detectionCycle = detectionCycles.get(k);
                        String detectionName = detectionCycle.getCategoryName().replaceAll(" ", "");
                        if (detectionName.equals(s)) {  //根据名称匹配id
                            personVo.setDetectionCycleId(detectionCycle.getId());//类别id
                            break;
                        }
                    }
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、姓名： " + personVo.getPersonName() + " 类别为空");
                    throw new ServiceException(failureMsg.toString());
                }
                if (StringUtils.isNull(personVo.getDetectionCycleId())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、姓名： " + personVo.getPersonName() + " 类别匹配失败");
                    throw new ServiceException(failureMsg.toString());
                }
                if (StringUtils.isNotNull(personVo.getCardId())) {
                    // 验证该人员是否存在
                    int i = personMapper.SelectCaridVo(personVo.getCardId());
                    if (i == 0) {
                        //新增
                        personVo.setSource("1"); //* 0新增1导入2小程序录入
                        personVo.setExamine(0); //审核通过/未审核 /未通过  0通过2未通过
                        personVo.setCreateTime(new Date());
                        personLists.add(personVo);
                        successNum++;
//                        successMsg.append("<br/>" + successNum + "、姓名： " + personVo.getPersonName() + " 导入成功");
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、姓名： " + personVo.getPersonName() + " 重复身份证号，身份证号为：" + personVo.getCardId());
                        throw new ServiceException(failureMsg.toString());
                    }
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、姓名： " + personVo.getPersonName() + " 身份证号为空");
                    throw new ServiceException(failureMsg.toString());
                }
            } catch (Exception e) {
                throw new ServiceException(failureMsg.toString());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            for (PersonVo personVo : personLists) {
                personMapper.insertPersonVo(personVo);
            }
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();
    }

    /**
     * 身份证号校验
     *
     * @param person
     * @return 结果
     */
    @Override
    public List<Person> SelectCarid(Person person) {
        return personMapper.SelectCarid(person);
    }

    /**
     * Excel校验
     *
     * @param personList      疫情信息
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return
     */
    @Override
    public List<checkExcelVo> checkExcel(List<PersonVo> personList, Boolean isUpdateSupport) {
        List list = new ArrayList();
        if (StringUtils.isNull(personList) || personList.size() == 0) {
            list.add(new checkExcelVo("", "", "校验数据不允许为空"));
            return list;
        }
        //查詢类别
        List<DetectionCycle> detectionCycles = detectionCycleMapper.selectDetectionCycleList(new DetectionCycle());
        //获取当前所有行业
        for (PersonVo personVo : personList) {
            //进行身份证号去重
            int asd = 0;
            for (PersonVo e : personList) {
                if (StringUtils.isNull(personVo.getCardId())) {
                    list.add(new checkExcelVo(personVo.getPersonName(), "", "身份证号为空"));
                }
                if (personVo.getCardId().equals(e.getCardId())) {
                    asd++;
                }
            }
            if (asd > 1) {
                list.add(new checkExcelVo(personVo.getPersonName(), personVo.getCardId(), "与该Excel中存在重复身份证号"));
            }
            List<SysDept> depts = deptService.selectDeptList(new SysDept());
            try {
                //行业匹配
                if (StringUtils.isNotEmpty(personVo.getDeptName())) {
                    String[] split = personVo.getDeptName().split("-");
                    int se = 0;
                    for (int a = 0; a < split.length; a++) {
                        String s = split[a].replaceAll(" ", "");//行业去空
                        for (int c = 0; c < depts.size(); c++) {
                            String s1 = depts.get(c).getDeptName().replaceAll(" ", "");
                            //最后一级
                            if (split.length == (a + 1)) {
                                if (s.equals(s1)) {
                                    personVo.setDeptId(depts.get(c).getDeptId());
                                    break;
                                }
                            }
                            if (s.equals(s1)) {
                                depts = deptService.selectDeptList(new SysDept(depts.get(c).getDeptId()));
                                se++;
                            }
                            if (depts.size() == (c + 1)) {
                                if (se == 0) {
                                    list.add(new checkExcelVo(personVo.getPersonName(), personVo.getCardId(), "部门不匹配，系统中没有该部门,部门名称为：" + s));
                                } else {
                                    se = 0;
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    list.add(new checkExcelVo(personVo.getPersonName(), personVo.getCardId(), "部门为空"));
                }
                //类别匹配
                String trim2 = personVo.getDetectionCycleName();
                if (StringUtils.isNotNull(trim2)) {
                    String s = trim2.replaceAll(" ", "");
                    for (int k = 0; k < detectionCycles.size(); k++) {
                        DetectionCycle detectionCycle = detectionCycles.get(k);
                        String detectionName = detectionCycle.getCategoryName().replaceAll(" ", "");
                        if (detectionName.equals(s)) {  //根据名称匹配id
                            personVo.setDetectionCycleId(detectionCycle.getId());//类别id
                            break;
                        }
                    }
                } else {
                    list.add(new checkExcelVo(personVo.getPersonName(), personVo.getCardId(), "类别为空"));
                }
                if (StringUtils.isNull(personVo.getDetectionCycleId())) {
                    list.add(new checkExcelVo(personVo.getPersonName(), personVo.getCardId(), "类别匹配失败"));
                }
                if (StringUtils.isNotNull(personVo.getCardId())) {
                    // 验证该人员是否存在
                    int i = personMapper.SelectCaridVo(personVo.getCardId());
                    if (i > 0) {
                        list.add(new checkExcelVo(personVo.getPersonName(), personVo.getCardId(), "与线上已有数据存在重复身份证号"));
                    }
                } else {
                    list.add(new checkExcelVo(personVo.getPersonName(), personVo.getCardId(), "身份证号为空"));
                }
            } catch (Exception e) {
                log.error(e + "");
                list.add(new checkExcelVo(personVo.getPersonName(), personVo.getCardId(), "程序存在bug,请联系管理员" + e));
            }
        }
        return list;
    }

    @Override
    public Integer selectPersonCount(Long deptId) {
        return personMapper.selectPersonCount(deptId);
    }


}
